<template>
  <a-modal
    width="800px"
    v-drag
    :destroyOnClose="true"
    :maskClosable="false"
    :title="title"
    :visible="visible"
    :bodyStyle="{ padding: '1px' }"
    @cancel="cancel"
  >
    <a-spin :spinning="spinning">
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="config.labelCol"
        :wrapper-col="config.wrapperCol"
      >
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="form.name" placeholder="请输入名称" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="图标" prop="icon">
          <eip-icon
            :name="form.icon"
            :theme="form.theme"
            @click="iconClick"
            @clear="iconClear"
          ></eip-icon>
        </a-form-model-item>
        <a-form-model-item label="使用类型" prop="useType">
          <a-select placeholder="请选择类型" allow-clear v-model="form.useType">
            <a-select-option :value="1">普通表单</a-select-option>
            <a-select-option :value="2">流程表单</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="form.useType == 2"
          label="归属分类"
          prop="typeId"
        >
          <a-select
            placeholder="请选择归属分类"
            allow-clear
            v-model="form.typeId"
            show-search
            :filter-option="filterOption"
          >
            <div slot="dropdownRender" slot-scope="menu">
              <v-nodes :vnodes="menu" />
              <a-divider style="margin: 4px 0" />
              <div style="padding: 4px 8px; cursor: pointer" @click="typeAdd">
                <a-icon type="plus" /> 新建分类
              </div>
            </div>
            <a-select-option v-for="t in type" :key="t.typeId">
              {{ t.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="打开类型" prop="openType">
          <a-select allow-clear v-model="form.openType">
            <a-select-option :value="0"> 当前页 </a-select-option>
            <a-select-option :value="2"> 新窗口 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </a-form-model-item>

        <a-form-model-item label="禁用">
          <a-switch v-model="form.isFreeze" />
        </a-form-model-item>

        <a-form-model-item label="排序号" prop="orderNo">
          <a-input-number
            id="inputNumber"
            style="width: 100%"
            placeholder="请输入排序号"
            v-model="form.orderNo"
            :min="0"
            :max="999"
          />
        </a-form-model-item>
      </a-form-model>
    </a-spin>

    <template slot="footer">
      <a-space>
        <a-button key="back" @click="cancel" :disabled="loading"
          ><a-icon type="close" />取消</a-button
        >
        <a-button key="submit" @click="save" type="primary" :loading="loading"
          ><a-icon type="save" />提交</a-button
        >
      </a-space>
    </template>

    <type-edit
      ref="typeedit"
      v-if="typeedit.visible"
      :visible.sync="typeedit.visible"
      :title="typeedit.title"
      :typeId="typeedit.typeId"
      :copy="typeedit.copy"
      @ok="initType"
    ></type-edit>
  </a-modal>
</template>
    
<script>
import typeEdit from "@/pages/system/type/edit";
import {
  tableExist,
  table,
  agileSave,
  agileSaveType,
  save,
  findById,
  listPublic,
  buttonSave,
  findByMenuId,
  systemType,
} from "@/services/system/agile/app/worksheet";
import eipIcon from "@/pages/common/usercontrol/eip-icon";
import { pinyin } from "pinyin-pro";
import { newGuid, emptyGuid } from "@/utils/util";
export default {
  components: {
    eipIcon,
    typeEdit,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  name: "edit",
  data() {
    return {
      config: {
        labelCol: { span: 3 },
        wrapperCol: { span: 20 },
      },
      type: [],
      form: {
        menuId: newGuid(),
        parentId: this.parentId,
        parentName: this.parentName,
        name: null,
        icon: null,
        theme: null,
        openType: 0,
        path: null,
        router: "agileappbuild",
        isShowMenu: true,
        haveMenuPermission: true,
        haveButtonPermission: true,
        haveDataPermission: true,
        haveFieldPermission: true,
        isFreeze: false,
        orderNo: 1,
        params: null,
        remark: null,
        isAppMenu: true,
        appMenuType: 2,
        useType: 2,
        typeId: undefined,
      },
      rules: {
        icon: [
          {
            required: true,
            message: "请选择图标",
            trigger: "blur",
          },
        ],
        useType: [
          {
            required: true,
            message: "请选择使用类型",
            trigger: ["blur", "change"],
          },
        ],
        typeId: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.form.useType == 2) {
                if (!value) {
                  callback(new Error("请选择归属分类"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
        ],
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              var py = pinyin(value, {
                toneType: "none",
                type: "array",
              });
              var model = this.eipTablePrefix;
              py.forEach((item) => {
                model += item
                  .toLowerCase()
                  .replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
              });
              //表名是否具有
              let param = {
                menuId: this.form.menuId,
                dataFromName: model,
              };
              tableExist(param).then((result) => {
                if (result.data) {
                  callback();
                } else {
                  callback(new Error("已存在"));
                }
              });
            },
            trigger: "blur",
          },
        ],
      },

      loading: false,
      spinning: false,
      agileSaveForm: {
        configId: undefined,
        name: undefined,
        orderNo: undefined,
        remark: undefined,
        useType: undefined,
        typeId: undefined,
      },
      listForm: {},

      typeedit: {
        visible: false,
        typeId: "",
        title: "",
        copy: false,
      },
    };
  },

  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Array,
    },
    title: {
      type: String,
    },
    copy: {
      type: Boolean,
      default: false,
    },
    menuId: {
      type: String,
    },
    parentId: {
      type: String,
    },
    parentName: {
      type: String,
    },
  },

  mounted() {
    this.find();
  },

  methods: {
    /**
     * 新增
     */
    typeAdd() {
      this.typeedit.typeId = null;
      this.typeedit.title = "新增类型配置";
      this.typeedit.visible = true;
      this.typeedit.copy = false;
    },

    /**
     * 取消
     */
    cancel() {
      this.$emit("update:visible", false);
    },
    /**
     *
     * @param {搜索} input
     * @param {*} option
     */
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 保存
     */
    async save() {
      let that = this;
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          //判断分类

          that.loading = true;
          that.$loading.show({ text: that.eipMsg.saveloading });
          that.form.menuId = that.copy ? newGuid() : that.form.menuId;
          //生成path
          // that.form.path = "/pages/agile/list/list";
          if (that.menuId) {
            var result = await save(that.form);
            if (result.code !== that.eipResultCode.success) {
              that.$message.error(result.msg);
              return false;
            }

            that.agileSaveForm.name = that.form.name;
            that.agileSaveForm.orderNo = that.form.orderNo;
            that.agileSaveForm.remark = that.form.remark;
            that.agileSaveForm.useType = that.form.useType;
            that.agileSaveForm.typeId = that.form.typeId;

            result = await agileSaveType(that.agileSaveForm);
            if (result.code == that.eipResultCode.success) {
              that.$message.success(result.msg);
              that.cancel();
              that.$emit("save", result);
            }
            that.loading = false;
            that.$loading.hide();
          } else {
            var py = pinyin(that.form.name, {
              toneType: "none",
              type: "array",
            });
            var model = this.eipTablePrefix;
            py.forEach((item) => {
              model += item
                .toLowerCase()
                .replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
            });
            var formSaveJson =
              '{"list":[],"config":{"layout":"horizontal","labelCol":{"xs":4,"sm":4,"md":4,"lg":4,"xl":4,"xxl":4},"wrapperCol":{"xs":18,"sm":18,"md":18,"lg":18,"xl":18,"xxl":18},"event":{"before":"","after":""},"api":{"before":"","after":""},"button":{"submit":{"name":"保存","success":0}},"hideRequiredMark": false,"width": "95","unit": "%","formWidth": "100","formWidthUnit": "%","top": "100","centered": false,"customStyle": ""}}';
            that.agileSaveForm = {
              configId: newGuid(),
              dataFromName: model,
              configType: 2,
              dataFrom: 0,
              name: that.form.name,
              orderNo: 1,
              isFreeze: false,
              remark: that.form.name,
              formCategory: 1,
              useType: that.form.useType,
              typeId: that.form.typeId,
              menuId: that.form.menuId,
              saveJson: formSaveJson,
              publicJson: formSaveJson,
            };

            var result = await table(that.agileSaveForm);
            if (result.code != that.eipResultCode.success) {
              that.$message.error(result.msg);
              that.loading = false;
              that.$loading.hide();
            }

            result = await agileSave(that.agileSaveForm);
            if (result.code != that.eipResultCode.success) {
              that.$message.error(result.msg);
              that.loading = false;
              that.$loading.hide();
            }

            result = await that.saveList();
            if (result.code != that.eipResultCode.success) {
              that.$message.error(result.msg);
              that.loading = false;
              that.$loading.hide();
            }

            result = await that.saveForm();
            if (result.code != that.eipResultCode.success) {
              that.$message.error(result.msg);
              that.loading = false;
              that.$loading.hide();
            }

            result = await that.jsonPublic();
          }
        }
      });
    },

    /**
     * 列表配置
     */
    async saveList() {
      let that = this;
      var py = pinyin(that.form.name, {
        toneType: "none",
        type: "array",
      });
      var model = this.eipTablePrefix;
      py.forEach((item) => {
        model += item
          .toLowerCase()
          .replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
      });
      var listJson = {
        columns: [], //表格控件
        search: {
          num: 3, //显示个数
          columns: [], //查询条件
        },
        filter: [], //筛选条件
        button: [], //按钮
        style: {
          rowHeight: 40,
          paging: true,
          columnIsCurrent: true,
          rowIsCurrent: true,
          select: "checkbox",
          border: "full",
        },
        phone: {
          style: 1, //卡片模版
          title: undefined, //标题
          subTitle: undefined, //摘要
          columns: [], //显示字段
          cover: undefined, //封面
          coverPosition: undefined, //显示位置
          coverShowType: undefined, //显示方式
        },
      };
      that.listForm = {
        configId: newGuid(),
        dataFrom: 0,
        dataFromName: model,
        name: "全部",
        orderNo: 1,
        configType: 1,
        isFreeze: false,
        remark: that.form.name,
        editConfigId: that.agileSaveForm.configId,
        saveJson: JSON.stringify(listJson),
        publicJson: JSON.stringify(listJson),
        menuId: that.form.menuId,
      };
      return await agileSave(that.listForm);
    },

    /**
     * 保存菜单
     */
    async saveForm() {
      let that = this;
      that.form.path = "/appbuild/" + that.form.menuId;
      return await save(that.form);
    },

    /**
     * 发布
     */
    async jsonPublic() {
      let that = this;
      var result = await listPublic(that.listForm);

      if (result.code != that.eipResultCode.success) {
        that.$message.error(result.msg);
        that.loading = false;
        that.$loading.hide();
      }
      var result = await listPublic(that.agileSaveForm);

      if (result.code != that.eipResultCode.success) {
        that.$message.error(result.msg);
        that.loading = false;
        that.$loading.hide();
      }

      that.saveButton();
    },

    /**
     * 生成默认按钮
     */
    saveButton() {
      var buttons = [];
      let that = this;
      if (that.form.useType == 1) {
        buttons = [
          {
            menuButtonId: emptyGuid(),
            menuId: this.form.menuId,
            menuName: this.form.name,
            type: "primary",
            name: "新增",
            icon: "plus",
            theme: "outlined",
            method: "add",
            script: null,
            orderNo: 1,
            isFreeze: false,
            remark: null,
          },
          {
            menuButtonId: emptyGuid(),
            menuId: this.form.menuId,
            menuName: this.form.name,
            type: "primary",
            name: "编辑",
            icon: "edit",
            theme: "outlined",
            method: "update",
            script: null,
            orderNo: 2,
            isFreeze: false,
            remark: null,
          },
          {
            menuButtonId: emptyGuid(),
            menuId: this.form.menuId,
            menuName: this.form.name,
            type: "danger",
            name: "批量删除",
            icon: "delete",
            theme: "outlined",
            method: "del",
            script: null,
            orderNo: 3,
            isFreeze: false,
            remark: null,
          },
          {
            menuButtonId: emptyGuid(),
            menuId: this.form.menuId,
            menuName: this.form.name,
            type: "primary",
            name: "复制",
            icon: "copy",
            theme: "outlined",
            method: "copy",
            script: null,
            orderNo: 4,
            isFreeze: false,
            remark: null,
          },
        ];
      } else {
        buttons = [
          {
            menuButtonId: emptyGuid(),
            menuId: this.form.menuId,
            menuName: this.form.name,
            type: "primary",
            name: "发起",
            icon: "plus",
            theme: "outlined",
            method: "workflowStart",
            script: null,
            orderNo: 0,
            isFreeze: false,
            remark: null,
          },
          {
            menuButtonId: emptyGuid(),
            menuId: this.form.menuId,
            menuName: this.form.name,
            type: "primary",
            name: "取消",
            icon: "close-circle",
            theme: "outlined",
            method: "workflowRevoke",
            script: null,
            orderNo: 2,
            isFreeze: false,
            remark: null,
          },
          {
            menuButtonId: emptyGuid(),
            menuId: this.form.menuId,
            menuName: this.form.name,
            type: "danger",
            name: "批量删除",
            icon: "delete",
            theme: "outlined",
            method: "del",
            script: null,
            orderNo: 3,
            isFreeze: false,
            remark: null,
          },
        ];
      }

      var saveNumber = 0;
      buttons.forEach((item) => {
        buttonSave(item).then(function (result) {
          if (result.code === that.eipResultCode.success) {
            saveNumber += 1;
            if (saveNumber == buttons.length) {
              that.loading = false;
              that.$loading.hide();
              that.$message.success(result.msg);
              that.cancel();
              that.$emit("save", result);
            }
          } else {
            that.loading = false;
            that.$loading.hide();
            that.$message.error(result.msg);
          }
        });
      });
    },

    /**
     * 初始化类型
     */
    async initType() {
      var result = await systemType();
      if (result.code === this.eipResultCode.success) {
        this.type = result.data;
      }
    },

    /**
     * 根据Id查找
     */
    async find() {
      let that = this;
      that.spinning = true;
      await this.initType();
      if (this.menuId) {
        var result = await findById(this.menuId);
        if (that.copy) {
          result.data.orderNo += 1;
        }
        let form = result.data;
        form.parentId = form.parentName == "" ? undefined : form.parentId;
        result = await findByMenuId({ menuId: this.menuId, configType: 2 });
        if (result.code === this.eipResultCode.success) {
          var agileData = result.data[0];
          form.useType = agileData.useType;
          form.typeId = agileData.typeId ? agileData.typeId : undefined;

          that.agileSaveForm = {
            configId: agileData.configId,
            name: agileData.name,
            orderNo: form.orderNo,
            remark: form.remark,
            useType: agileData.useType,
            typeId: agileData.typeId,
          };
        }
        that.form = form;
      }
      that.spinning = false;
    },

    /**
     *图标点击
     */
    iconClick(icon) {
      this.form.icon = icon.name;
      this.form.theme = icon.theme;
    },

    /**
     * 清空图标
     */
    iconClear() {
      this.form.icon = null;
      this.form.theme = null;
    },
  },
};
</script>
    
    <style lang="less" scoped></style>
    